package com.gao.api.gate.quick.proto.server;

import com.gao.api.gate.quick.proto.config.HttpServerConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.HashMap;
import java.util.Map;

/**
 * <p></p>
 *
 * @author gaoshuangwen
 * @since 2022/01/07 22:04
 */
public class HttpServerBootstrap {
    private int port;
    private final EventLoopGroup boss;
    private final EventLoopGroup work;
    private final ChannelInitializer<Channel> childChannelInitializer;

    public HttpServerBootstrap(HttpServerConfig httpServerConfig,
                               ChannelInitializer<Channel> childChannelInitializer) {
        this.port = httpServerConfig.getPort();
        boss=new NioEventLoopGroup(httpServerConfig.getBossThreadSize());
        work=new NioEventLoopGroup(httpServerConfig.getWorkThreadSize());
        this.childChannelInitializer = childChannelInitializer;
    }
    public ChannelFuture buildServerBootstrap() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap().group(boss, work);
        serverBootstrap.channel(NioServerSocketChannel.class);

        Map<ChannelOption<?>, Object> channelOptions = new HashMap<>();
        channelOptions.put(ChannelOption.SO_BACKLOG, 128);
        channelOptions.put(ChannelOption.SO_LINGER, -1);
        channelOptions.put(ChannelOption.TCP_NODELAY, true);
        channelOptions.put(ChannelOption.SO_KEEPALIVE, true);
  /*      serverBootstrap.handler(new NewConnHandler());
        serverBootstrap.childHandler(channelInitializer);*/
        serverBootstrap.childHandler(childChannelInitializer);
        serverBootstrap.validate();
        // Bind and start to accept incoming connections.
        return serverBootstrap.bind(port).sync();

    }

    public EventLoopGroup getBoss() {
        return boss;
    }

    public EventLoopGroup getWork() {
        return work;
    }
}
